package com.luo.gmall.cart.listener;

import com.luo.gmall.cart.feign.GmallPmsClient;
import com.luo.gmall.pms.entity.SkuEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author Zoro
 * @date 2021年11月24
 */
@Component
public class CartListener {

    @Autowired
    private GmallPmsClient gmallPmsClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String CURRENT_PRICE_PREFIX = "skuId:price:";


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("PMS_CART_PRICE"),
            exchange = @Exchange(value = "PMS_SPU_EXCHANGE", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC),
            key = ("item.update")
    ))
    public void asyncPrice(Long spuId, Channel channel, Message message) throws IOException {

        if (spuId == null) {
            // 确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }

        // 获取spu下所有的skuId
        List<SkuEntity> skuEntities = gmallPmsClient.querySkuBySpuId(spuId).getData();
        if (CollectionUtils.isEmpty(skuEntities)) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }

        // 遍历循环修改已存在的skuId对应的价格
        skuEntities.forEach(skuEntity -> redisTemplate.opsForValue().setIfPresent(CURRENT_PRICE_PREFIX + skuEntity.getId(), skuEntity.getPrice().toString()));


    }
}
